package com.ls.fw.mvc.springmvc.support.security;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;
 
/**
 * <form method="post" action="foobar">
   <df:csrfToken />
</form>
<c:url value="/foobar">
  <c:param name="${df:csrfTokenParameter()}">
    <df:csrfToken plainToken="true"/>
  </c:param>
</c:url>
js：
function isInvalidCSRFToken = function(xhr) {
    var rv = false;
    if(xhr.status == 403 && xhr.getResponseHeader('X-DailyFratze-InvalidCSRFToken') == 'true') {            
        alert($('Session is invalid').text());
        rv = true;
    }
    return rv;
}
 */
/**
 * Creates a hidden input field with the CSRF Token
 * @author michael.simons, 2011-09-20
 */
public class CSRFTokenTag extends TagSupport {
	private static final long serialVersionUID = 745177955805541350L;
 
	private boolean plainToken = false;
	CSRFTokenService csrfTokenService = null;
	@Override
	public int doStartTag() throws JspException {
		//csrfTokenService = HelperRegistry.getHelper(super.pageContext.getServletContext(), super.pageContext.getRequest(), CSRFTokenService.class, "csrfTokenService");
		final String token = csrfTokenService.getTokenFromSession((HttpServletRequest) super.pageContext.getRequest());
		if(!StringUtils.isBlank(token))
			try {
				if(plainToken)
					pageContext.getOut().write(token);
				else
					pageContext.getOut().write(String.format("<input type=\"hidden\" name=\"%1$s\" id=\"%1$s\" value=\"%2$s\" />", CSRFTokenService.TOKEN_PARAMETER_NAME, token));
			} catch (IOException e) {
			}
		return SKIP_BODY;
	}
 
	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}
 
	public boolean isPlainToken() {
		return plainToken;
	}
 
	public void setPlainToken(boolean plainToken) {
		this.plainToken = plainToken;
	}
 
	public static String getTokenParameterName() {
		return CSRFTokenService.TOKEN_PARAMETER_NAME;
	}
}